package com.tuliyou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tuliyou.common.util.Result;
import com.tuliyou.dto.PageInfo;
import com.tuliyou.entity.UniMajorEnrollment;
import com.tuliyou.mapper.UniMajorEnrollmentMapper;
import com.tuliyou.mapper.UniversityMapper;
import com.tuliyou.service.UniMajorEnrollmentService;
import com.tuliyou.vo.UniMajorEnrollmentVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UniMajorEnrollmentServiceImpl extends ServiceImpl<UniMajorEnrollmentMapper, UniMajorEnrollment> implements UniMajorEnrollmentService {

    @Resource
    private UniMajorEnrollmentMapper uniMajorEnrollmentMapper;

    @Resource
    private UniversityMapper universityMapper;

    @Override
    public Result<PageInfo<UniMajorEnrollmentVO>> getUniMajorEnrollments(Integer page, Integer size, String universityCode, Integer enrollYear) {
        // 当enrollYear不是2025时，大学代码不是传过来的2025年的大学代码，需要查询相应年份的大学代码
        if(enrollYear != 2025){
            // 先根据大学代码在大学表中查找对应的大学名称
            String universityName = universityMapper.getNameByCode(universityCode);
            // 再根据查到的大学名称和招生年份查找对应的大学代码
            universityCode  = universityMapper.getCodeByNameAndEnrollYear(universityName,enrollYear);
        }
        // 设置分页参数
        PageHelper.startPage(page, size);
        // 执行查询
        List<UniMajorEnrollment> uniMajorEnrollmentList = uniMajorEnrollmentMapper.getUniMajorEnrollments(universityCode,enrollYear);
        // 关键：先将查询结果强转为Page<UniMajorEnrollment>，保留分页信息
        Page<UniMajorEnrollment> uniMajorEnrollmentPage = (Page<UniMajorEnrollment>) uniMajorEnrollmentList;
        // 转换DTO：基于原始Page的list进行stream映射（不破坏分页信息）
        List<UniMajorEnrollmentVO> uniMajorEnrollmentVOList = uniMajorEnrollmentPage.stream().map(UniMajorEnrollmentVO::fromUniMajorEnrollment).toList();
        // 封装PageInfo对象
        PageInfo<UniMajorEnrollmentVO> pageInfo = new PageInfo<>();
        pageInfo.setCurrent(uniMajorEnrollmentPage.getPageNum()); // 当前页码
        pageInfo.setSize(uniMajorEnrollmentPage.getPageSize()); // 每页条数
        pageInfo.setTotal(uniMajorEnrollmentPage.getTotal()); // 总记录数
        pageInfo.setPages(uniMajorEnrollmentPage.getPages()); // 总页数
        pageInfo.setRecords(uniMajorEnrollmentVOList); // 当前页VO列表
        return Result.success(pageInfo);
    }

    @Override
    public Result<UniMajorEnrollmentVO> getUniMajorEnrollmentDetail(Long id) {
        UniMajorEnrollment uniMajorEnrollment = uniMajorEnrollmentMapper.getUniMajorEnrollmentDetail(id);
        UniMajorEnrollmentVO uniMajorEnrollmentVO = UniMajorEnrollmentVO.fromUniMajorEnrollment(uniMajorEnrollment);
        return Result.success(uniMajorEnrollmentVO);
    }
}
